/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SearchPanel.java
 *
 * Created on 24.Eki.2011, 04:23:54
 */
package xcompany.userInterface;

import java.io.IOException;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import xcompany.control.DatabaseControl;
import xcompany.lists.ClaimList;
import xcompany.structures.Claim;

/**
 *
 * @author Alp Sayin
 */
public class SearchPanel extends javax.swing.JPanel
{

    /** Creates new form SearchPanel */
    ClaimList searchResults;
    private ComboBoxModel getResultsComboBoxModel()
    {
        DefaultComboBoxModel dcbm = new DefaultComboBoxModel(SearchOption.values());
        return dcbm;
    }
    private enum SearchOption
    {
        ID, Username, Customer_Name, Customer_Surname, Customer_NameSurname, ClaimHandler_Name, ClaimHandler_Surname, ClaimHandler_NameSurname, Financer_Name, Financer_Surname, Financer_NameSurname, Date_Interval, Damage_Interval, Status;
        @Override public String toString()
        {
            return super.toString().replace(" ", "_");
        }
    }
    public SearchPanel()
    {
        try
        {
            searchResults = DatabaseControl.getAllClaims();
        }
        catch (IOException ex)
        {
            Logger.getLogger(SearchPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (ClassNotFoundException ex)
        {
            Logger.getLogger(SearchPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        initComponents();
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        typeComboBox = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        searchField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        resultsTable = new javax.swing.JTable(){
            @Override public boolean isCellEditable(int row, int col)
            {
                return false;
            }
        };
        searchButton = new javax.swing.JButton();
        clearButton = new javax.swing.JButton();

        jLabel1.setText("Search by:");

        typeComboBox.setModel(getResultsComboBoxModel());
        typeComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                typeComboBoxActionPerformed(evt);
            }
        });

        jLabel2.setText("Search for:");

        searchField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchFieldActionPerformed(evt);
            }
        });

        resultsTable.setModel(getResultsTableModel());
        resultsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(resultsTable);

        searchButton.setText("Search");
        searchButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchButtonActionPerformed(evt);
            }
        });

        clearButton.setText("Clear Results");
        clearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 482, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addGap(28, 28, 28)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(searchButton, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(clearButton))
                            .addComponent(typeComboBox, 0, 400, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(typeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(searchField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchButton)
                    .addComponent(clearButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 271, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void searchButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_searchButtonActionPerformed
    {//GEN-HEADEREND:event_searchButtonActionPerformed
        try
        {
            String s = searchField.getText();
            searchResults = DatabaseControl.getAllClaims();
            ClaimList newSearchResults = new ClaimList();
            Object[] all = searchResults.getClaimList().values().toArray();
            for(int i=0; i<searchResults.getClaimList().size(); i++)
            {
                Claim c = (Claim)all[i];
                switch((SearchOption)typeComboBox.getSelectedItem())
                {
                    case ID: 
                        if(s.equalsIgnoreCase(String.valueOf(c.getId())))
                            newSearchResults.add(c);
                        break;
                    case Status:
                        if(s.equalsIgnoreCase(c.getStatus().toString()))
                            newSearchResults.add(c);
                        break;
                    case Damage_Interval:
                        double damage = c.getDamage();
                        double damage1 = Double.parseDouble(s.split("-")[0]);
                        double damage2 = Double.parseDouble(s.split("-")[1]);
                        if(damage1 <= damage2)
                        {
                            if(damage>=damage1 && damage<=damage2)
                                newSearchResults.add(c);
                        }
                        else
                        {
                            if(damage<=damage1 && damage>=damage2)
                                newSearchResults.add(c);
                        }
                        break;
                    case Date_Interval:
                        Calendar cal1 = Calendar.getInstance();
                        cal1.set(Calendar.DATE, Integer.parseInt(s.split("-")[0].split("/")[0]));
                        cal1.set(Calendar.MONTH, Integer.parseInt(s.split("-")[0].split("/")[1]));
                        cal1.set(Calendar.YEAR, Integer.parseInt(s.split("-")[0].split("/")[2]));
                        Calendar cal2 = Calendar.getInstance();
                        cal2.set(Calendar.DATE, Integer.parseInt(s.split("-")[1].split("/")[0]));
                        cal2.set(Calendar.MONTH, Integer.parseInt(s.split("-")[1].split("/")[1]));
                        cal2.set(Calendar.YEAR, Integer.parseInt(s.split("-")[1].split("/")[2]));
                        if(cal1.before(cal2))
                        {
                            if(c.getDateOfCrash().after(cal1) && c.getDateOfCrash().before(cal2))
                                newSearchResults.add(c);
                        }    
                        else
                        {
                            if(c.getDateOfCrash().before(cal1) && c.getDateOfCrash().after(cal2))
                                newSearchResults.add(c);
                        }
                        break;
                    case Username:
                        if(s.equalsIgnoreCase(c.getOwner().getUsername()))
                            newSearchResults.add(c);
                        if(c.getClaimHandler()!=null)
                            if(s.equalsIgnoreCase(c.getClaimHandler().getUsername()))
                                newSearchResults.add(c);
                        if(c.getFinancer()!=null)
                            if(s.equalsIgnoreCase(c.getFinancer().getUsername()))
                                newSearchResults.add(c);
                        break;
                    case Customer_Name:
                        if(s.equalsIgnoreCase(c.getOwner().getName()))
                            newSearchResults.add(c);
                        break;
                    case Customer_Surname:
                        if(s.equalsIgnoreCase(c.getOwner().getSurname()))
                            newSearchResults.add(c);
                        break;
                    case Customer_NameSurname:
                        if(s.equalsIgnoreCase(c.getOwner().getName()+" "+c.getOwner().getSurname()))
                            newSearchResults.add(c);
                        break;
                    case ClaimHandler_Name:
                        if(c.getClaimHandler()!=null)
                            if(s.equalsIgnoreCase(c.getClaimHandler().getName()))
                                newSearchResults.add(c);
                        break;
                    case ClaimHandler_Surname:
                        if(c.getClaimHandler()!=null)
                            if(s.equalsIgnoreCase(c.getClaimHandler().getSurname()))
                                newSearchResults.add(c);
                        break;
                    case ClaimHandler_NameSurname:
                        if(c.getClaimHandler()!=null)
                            if(s.equalsIgnoreCase(c.getClaimHandler().getName()+" "+c.getClaimHandler().getSurname()))
                                newSearchResults.add(c);
                        break;
                    case Financer_Name:
                        if(c.getFinancer()!=null)
                            if(s.equalsIgnoreCase(c.getFinancer().getName()))
                                newSearchResults.add(c);
                        break;
                    case Financer_Surname:
                        if(c.getFinancer()!=null)
                            if(s.equalsIgnoreCase(c.getFinancer().getSurname()))
                                newSearchResults.add(c);
                        break;
                    case Financer_NameSurname:
                        if(c.getFinancer()!=null)
                            if(s.equalsIgnoreCase(c.getFinancer().getName()+" "+c.getFinancer().getSurname()))
                                newSearchResults.add(c);
                        break;
                    default: JOptionPane.showMessageDialog(this, "Invalid Search Type", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
            searchResults = newSearchResults;
            getResultsTableModel();
        }
        catch(NumberFormatException nfe)
        {
            JOptionPane.showMessageDialog(this, "Error in number", "Incorrect Parameter", JOptionPane.ERROR_MESSAGE);
        }
        catch (IOException ex)
        {
            Logger.getLogger(SearchPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (ClassNotFoundException ex)
        {
            Logger.getLogger(SearchPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_searchButtonActionPerformed

    private void searchFieldActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_searchFieldActionPerformed
    {//GEN-HEADEREND:event_searchFieldActionPerformed
        searchButtonActionPerformed(evt);
    }//GEN-LAST:event_searchFieldActionPerformed

    private void clearButtonActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_clearButtonActionPerformed
    {//GEN-HEADEREND:event_clearButtonActionPerformed
        try
        {
            searchResults = DatabaseControl.getAllClaims();
            getResultsTableModel();
        }
        catch (IOException ex)
        {
            Logger.getLogger(SearchPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
        catch (ClassNotFoundException ex)
        {
            Logger.getLogger(SearchPanel.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_clearButtonActionPerformed

    private void typeComboBoxActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_typeComboBoxActionPerformed
    {//GEN-HEADEREND:event_typeComboBoxActionPerformed
        switch((SearchOption)typeComboBox.getSelectedItem())
        {
            case Damage_Interval: searchField.setText("0-2000"); break;
            case Date_Interval: searchField.setText("1/1/1970-24/10/2011"); break;
                default: break;
        }
    }//GEN-LAST:event_typeComboBoxActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton clearButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable resultsTable;
    private javax.swing.JButton searchButton;
    private javax.swing.JTextField searchField;
    private javax.swing.JComboBox typeComboBox;
    // End of variables declaration//GEN-END:variables
    private TableModel getResultsTableModel()
    {
        String[] cols = {"ID","Customer","Date","Damage","Description","Garage","Claim Handler","Financer"};
        DefaultTableModel dtm = new DefaultTableModel(cols, 0);
        for(Claim c : searchResults.getClaimList().values())
        {
            String[] vals = new String[cols.length];
            vals[0] = ""+c.getId();
            vals[1] = c.getOwner().getName()+" "+c.getOwner().getSurname();
            vals[2] = c.getDateOfCrash().get(Calendar.DATE)+"/"+c.getDateOfCrash().get(Calendar.MONTH)+"/"+c.getDateOfCrash().get(Calendar.YEAR);
            vals[3] = ""+c.getDamage();
            vals[4] = c.getDescription();
            if(c.getGarage()!=null)
                vals[5] = c.getGarage().getName() + " - "+ c.getGarage().getAddress();
            else
                vals[5] = "n/a";
            if(c.getClaimHandler()!=null)
                vals[6] = c.getClaimHandler().getName()+" "+c.getClaimHandler().getSurname();
            else
                vals[6] = "n/a";
            if(c.getFinancer()!=null)
                vals[7] = c.getFinancer().getName()+" "+c.getFinancer().getSurname();
            else
                vals[7] = "n/a";
            dtm.addRow(vals);
        }
        resultsTable.setModel(dtm);
        return dtm;
    }
}
